package sg.edu.nus.comp.icreate.ivletalk.forum;

import java.util.List;

import sg.edu.nus.comp.icreate.ivletalk.BaseActivity;
import sg.edu.nus.comp.icreate.ivletalk.R;
import sg.edu.nus.comp.icreate.ivletalk.User;
import sg.edu.nus.comp.icreate.ivletalk.module.ElementType;
import sg.edu.nus.comp.icreate.ivletalk.module.MainActivity;
import sg.edu.nus.comp.icreate.ivletalk.utils.net.DataPuller;
import sg.edu.nus.comp.icreate.ivletalk.voice.VoiceCommand;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;

public abstract class ForumBaseActivity extends BaseActivity {
	private static final int INDEX_MENU_ITEM_NEW_POST = 2;
	protected int modulePosition;
	protected Forum forum;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuItem menuItem = menu.getItem(INDEX_MENU_ITEM_NEW_POST);
		if (!((Forum) MainActivity.modules.get(modulePosition).getElements().get(ElementType.FORUM)).getHeadings().isEmpty())
			menuItem.setVisible(true);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.actionNewPost) {
			Intent intent = new Intent(getApplicationContext(), NewPostActivity.class);
			intent.putExtra(NewPostActivity.EXTRA_NAME_IS_REPLY, false);
			intent.putExtra(MainActivity.EXTRA_NAME_MODULE_POSITION, modulePosition);
			startActivityForResult(intent, NewPostActivity.REQUEST_CODE_NEW_POST);
			return true;
		} else {
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == NewPostActivity.REQUEST_CODE_NEW_POST)
			handleActionRefresh();
	}

	protected void getThreads() throws Exception {
		String url = "https://ivle.nus.edu.sg/api/Lapi.svc/Forum?APIKey=" + MainActivity.APIKEY + "&AuthToken=" + User.getInstance().getToken() + "&ForumID="
				+ forum.getId() + "&Duration=0&IncludeThreads=true&output=xml";
		DataPuller threadListPuller = new DataPuller(new ForumXmlParser());
		threadListPuller.execute(url);
		@SuppressWarnings("unchecked")
		List<Heading> list = (List<Heading>) threadListPuller.get();
		forum.getHeadings().clear();
		forum.getHeadings().addAll(list);
	}

	protected void goToItem(int position) {
		// do nothing
	}

	@Override
	public boolean executeMenuVoiceCommand(String cmd) {
		super.executeMenuVoiceCommand(cmd);
		if (cmd.equals(VoiceCommand.NEW.getPattern())) {
			return goNewPost();
		}
		return false;

	}

}
